package com.noodles.mall.controller;

import com.noodles.mall.entity.Cart;
import com.noodles.mall.service.CartService;
import com.noodles.mall.web.JsonResult;
import com.noodles.mall.web.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 购物车 **/
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /** 增加 **/
    @RequestMapping("/insert")
    public JsonResult insert(@RequestBody Cart cart) {
        System.out.println("CartController: insert");
        System.out.println("cart: "+cart);
        return cartService.selectOne(cart.getUserId(),cart.getItemId()) !=null // 查询是否存在相同数据
                ? JsonResult.error(State.ERR_EXIST)
                : (cartService.insert(cart) ? JsonResult.success() : JsonResult.error(State.ERR_SQL));
    }

    /** 删除: 批量 **/
    @RequestMapping("/delete")
    public JsonResult delete(@RequestBody List<Integer> idList) {
        System.out.println("CartController: deleteBatchCart");
        System.out.println("idList: "+idList);
        return cartService.delete(idList)
                ? JsonResult.success() : JsonResult.error(State.ERR_SQL);
    }

    /** 修改: 只修改商品数量 **/
    @RequestMapping("/update") //
    public JsonResult updateItemCount(@RequestBody Cart cart) {
        System.out.println("CartController: updateCart");
        System.out.println("cart: "+cart);
        return cartService.update(cart)
                ? JsonResult.success() : JsonResult.error(State.ERR_SQL);
    }

    /** 查询列表: **/
    @RequestMapping("/selectList/{userId}")
    public JsonResult selectList(@PathVariable(value = "userId") Integer userId) {
        System.out.println("CartController: selectByUserId");
        System.out.println("userId: "+userId);
        List<Cart> cartList = cartService.selectList(userId);
        return JsonResult.success(cartList);
    }

    /** 查找: 商品种数 **/
    @RequestMapping("/selectCount/{userId}")
    public JsonResult selectCount(@PathVariable(value = "userId") Integer userId) {
        System.out.println("CartController: selectCartCount");
        System.out.println("userId: "+userId);
        int count = cartService.selectCount(userId);
        return JsonResult.success(count);
    }

}
